package com.ssm.reader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.reader.entity.Book;
import com.ssm.reader.entity.Evaluation;
import com.ssm.reader.entity.MemberReadState;
import com.ssm.reader.mapper.BookMapper;
import com.ssm.reader.mapper.EvaluationMapper;
import com.ssm.reader.mapper.MemberReadStateMapper;
import com.ssm.reader.service.BookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/*
 *
 *
 *@data 2022-04-29
 */
@Service("bookService")
@Transactional(propagation = Propagation.NOT_SUPPORTED,readOnly = true)
public class BookServiceImpl implements BookService {
    @Resource
    private BookMapper bookMapper;

    @Resource
    private MemberReadStateMapper memberReadStateMapper;

    @Resource
    private EvaluationMapper evaluationMapper;

    public IPage<Book> paging(Long categoryId, String order,Integer page, Integer rows) {
        //分页查询
        Page<Book> p = new Page<Book>(page,rows);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<Book>();
        if (categoryId !=null && categoryId != -1){
            queryWrapper.eq("category_id",categoryId);
        }
        if (order != null){
            if (order.equals("quantity")){
                queryWrapper.orderByDesc("evaluation_quantity");
            }else if(order.equals("score")){
                queryWrapper.orderByDesc("evaluation_score");

            }

        }
        IPage<Book> bookPage = bookMapper.selectPage(p, queryWrapper);
        return bookPage;
    }

    public Book selectById(Long bookId) {
        Book book = bookMapper.selectById(bookId);
        return book;
    }

    @Transactional//开启事务
    public void updateEvaluation() {
        bookMapper.updateEvaluation();//基于mvc逐级调用，这是一个开发规范，利于代码维护
    }

    //创建新的图书、
    @Transactional//开启事务
    public Book createBook(Book book) {
       bookMapper.insert(book);
       return book;
    }

    //更新图书
    @Transactional//开启事务
    public Book updateBook(Book book){
        bookMapper.updateById(book);
        return book;

    }
    @Transactional//开启事务
    public void deleteBook(Long bookId) {
        bookMapper.deleteById(bookId);
        QueryWrapper<MemberReadState> memberReadStateQueryWrapper = new QueryWrapper<MemberReadState>();
        memberReadStateQueryWrapper.eq("book_id",bookId);
        memberReadStateMapper.delete(memberReadStateQueryWrapper);
        QueryWrapper<Evaluation> evaluationQueryWrapper = new QueryWrapper<Evaluation>();
        evaluationQueryWrapper.eq("book_id",bookId);
        evaluationMapper.delete(evaluationQueryWrapper);

    }


}
